from student import Student
class StudentManager:

    def __init__(self):
        self.students_dict = {}

    def startup(self):
        self.load_from_file("./data.txt")

    def load_from_file(self, file):
        """从指定文件初始化数据"""
        f = open(file, 'r', encoding='utf-8')
        for line in f.readlines():
            # 去掉最后的换行\n
            student_info = line[:-1].split(',')
            id = student_info[0]
            name = student_info[1]
            score = student_info[2]
            student = Student(id, name, score)
            self.students_dict[id] = student
        f.close()

    def save_to_file(self, file):
        """保存数据到文件"""
        student_list = self.students_dict.values()
        f = open(file, "w", encoding="UTF-8")
        for student in student_list:
            f.write(str(student)+"\n")
        f.close()

    def add_student(self):
        """添加一个学生"""
        id = input("请输入学号: ")
        name = input("请输入姓名: ")
        score = input("请输入分数: ")
        if id in self.students_dict.keys():
            print("学生已存在")
            return
        else:
            student = Student(id, name, score)
            self.students_dict[id] = student
            print("学生{}添加成功".format(id))

    def show_all(self):

        # 判断系统中是否有学生信息
        if len(self.students_dict) <= 0:
            # 如果没有,就提示"系统中还没有学生信息!!!"
            print("系统中还没有学生信息!!!\n")
        else:
            # 如果有
            # 先打印表头,一条线
            print("学号".ljust(14) + "姓名".ljust(15) + "分数".ljust(15))
            print("-" * 45)
            # 4.2 遍历列表,打印每个学生,一个学生打印成干一行
            for student in self.students_dict.values():
                id = student.id
                name = student.name
                score = student.score
                print(id.ljust(15) + name.ljust(15) + score.ljust(15))
            # 4.3 打印一条线
            print("-" * 45)

if __name__ == '__main__':
    student_manager = StudentManager()
    student_manager.startup()


